package net.lzzy.practicesapi1.web;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import net.lzzy.practicesapi1.constants.ApiConstant;
import net.lzzy.practicesapi1.constants.Messages;
import net.lzzy.practicesapi1.entities.User;
import net.lzzy.practicesapi1.services.UserService;
import net.lzzy.practicesapi1.utils.FileUtil;
import net.lzzy.practicesapi1.utils.StringUtil;
import net.lzzy.practicesapi1.web.models.ApiResult;
import net.lzzy.practicesapi1.web.models.LoginInfo;
import net.lzzy.practicesapi1.web.models.RegisterInfo;
import net.lzzy.practicesapi1.web.models.VmUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;
@Api(tags = "用户认证")
@CrossOrigin
@RestController
@RequestMapping(ApiConstant.ROUTE_AUTH_ROOT)
public class AuthApiController {
    private final UserService service;
    @Autowired
    public AuthApiController(UserService service) {
        this.service = service;
    }
    /**
     * PathVariable 处理URL模板参数（<a href=http://localhost/list?page=1&size=5>...</a >）
     * RequestParam处理；1.URL查询参数2.表单提交参数
     * RequestBody处理POST请求体，以JSON提交来的数据
     * RequestParam处理基本数据类型的参数，因为复杂类型的数据需要开发者自己解析，处理一般的Get请求或表单提交时的Post请求
     * RequestBody处理复杂的数据类型参数，处理前端发送的JSON，处理敏感数据如用户密码等（因为请求体相对于URL参数不易于拦截）
     * RequestBody处理一般的Post请求和Put请求
     */
    @ApiOperation("登录")
    @ApiImplicitParam(name = "info", value = "用户登录参数" , required = true ,
            dataType = "LoginInfo" , dataTypeClass = LoginInfo.class, paramType = "body")
    @PostMapping(value=ApiConstant.ROUTE_AUTH_LOGIN,produces =ApiConstant.API_PRODUCES )
    public ApiResult login(@RequestBody LoginInfo info){
        String userName=info.getUsername();
        String password=info.getPassword();
        String salt=service.getSalt(userName);
        User user=service.check(userName, StringUtil.md5Encode(password,salt));
        if (user==null){
            return new ApiResult(false, Messages.WRONG_PASSWORD.toString(), null);
        }if (user.getType()<0){
            return new ApiResult(false,Messages.USER_BANNED.toString(), null);
        }
        VmUser vmUser=VmUser.apiLogin(user);
        return new ApiResult(true,Messages.SUCCESS.toString(), vmUser);
    }

    @ApiOperation("检查用户是否已存在")
    @ApiImplicitParam(name = "user",value = "用户名", dataType = "String", dataTypeClass = String.class, paramType = "path")
    @GetMapping(ApiConstant.ROUTE_AUTH_EXISTS)
    public ApiResult isUserExists(@PathVariable String user){
        boolean exists=service.isUserNameOccupied(user);
        return new ApiResult(true,exists?"用户已存在":"",exists);
    }

    @ApiOperation("注册")
    @ApiImplicitParam(name = "info",value = "注册信息", dataType = "RegisterInfo" , dataTypeClass = RegisterInfo.class,
    required = true, paramType = "body")
    @PostMapping(ApiConstant.ROUTE_AUTH_REGISTER)
    public ApiResult register(@RequestBody RegisterInfo info) {
        String nick=info.getNick_name();
        String user=info.getUser_name();
        String phone=info.getPhone();
        String email=info.getEmail();
        String avatar=info.getAvatar();
        String password=info.getPassword();
        String salt= UUID.randomUUID().toString();
        boolean apply= info.isApply_teacher();
        if (StringUtil.isEmpty(nick)){
            nick=user;
        }
        if (StringUtil.isEmpty(nick) || StringUtil.isEmpty(avatar) ||
                StringUtil.isEmpty(phone) ||
                StringUtil.isEmpty(email) ||
                StringUtil.isEmpty(password)){
            return new ApiResult(false,Messages.MISS_ARGS.toString(), null);
        }
        if (!StringUtil.validPhone(phone)||!StringUtil.validMail(email)){
            return new ApiResult(false,Messages.INVALID_FORMAT.toString(), null);
        }
        if (service.isUserNameOccupied(user)) {
            return new ApiResult(false,Messages.USER_EXISTS.toString(), null);
        }
        User usr=new User();
        usr.setType(User.TYPE_STUDENT);
        usr.setUserName(user);
        usr.setEmail(email);
        usr.setAvatar(avatar);
        usr.setPhone(phone);
        usr.setNickName(nick);
        usr.setApplyTeacher(apply);
        usr.setSalt(salt);
        usr.setPassword(StringUtil.md5Encode(password,salt));
        VmUser vmUser=VmUser.apiLogin(service.register(usr));
        return new ApiResult(true,"注册成功",vmUser);

    }
    @Value("${user.pic}")
    private String path;

    @ApiOperation("上传文件")
    @ApiImplicitParam(name = "avatar", value = "文件上传参数", dataType = "MultipartFile",dataTypeClass = MultipartFile.class,
            required = true,paramType = "query")
    @PostMapping(ApiConstant.ROUTE_UPLOAD)
    public ApiResult upload(@RequestParam("avatar") MultipartFile file){
        JSONObject result = FileUtil.uploadWithRandomName(file,path);
        return new ApiResult(result.getBoolean(FileUtil.UPLOAD_PARAM_STATUS),
                result.getString(FileUtil.UPLOAD_PARAM_MESSAGE),
                result.getString(FileUtil.UPLOAD_PARAM_URL));
    }
}